import { Asset } from "cc";
import { LoaderBundle } from "./LoaderBundle";
import { Singleton } from "./Singleton";

export class LoaderManager extends Singleton{
    private _loader_list:LoaderBundle[];
    private _loader_cache_list:Map<string,LoaderBundle>;

    protected init(): void {
        this._loader_list=[]
        this._loader_cache_list=new Map();
    }
     /**
     * 获取已经加载的loader
     * @param path 
     * @returns 
     */
    public getLoaderBundle(path:string):LoaderBundle{
        return this._loader_cache_list.has(path) ? this._loader_cache_list.get(path) : null
    }
    /**
     * 获取对象池中的加载器
     * @returns 
     */
     private getLoader():LoaderBundle{
        let  loader:LoaderBundle=null
        for(let i=0;i<this._loader_list.length;i++){
            if(this._loader_list[i] && !this._loader_list[i].isUse){
                loader=this._loader_list[i];
                break
            }
        }
        if(!loader){
            loader=new LoaderBundle()
            this._loader_list.push(loader)
        }
        loader.isUse=true
        return loader
    }
    /**
     * 开始加载bundle
     * @param path 
     * @param params {version:"123456"}
     * @param progress 
     * @param finish 
     */
    public loadBundle(path:string,params:any,progress:(prv: number, total: number, item:LoaderBundle)=>void,finish:(loader:LoaderBundle)=>void){
        let  loader:LoaderBundle=this.getLoader();
        if(loader){
            this._loader_cache_list.set(path,loader)
            loader.loadBundle(path,params,progress,finish)
        }
    }
    public LoadBundleByParams(params:any,progress:(prv: number, total: number, item:LoaderBundle)=>void,finish:(loader:LoaderBundle)=>void){
        this.loadBundle(params.path,params,progress,finish)
    }
    /**
     * 获取资源类型
     * @param bundleName    bundle 名称
     * @param path          路径
     * @param type          加载资源类型
     * @returns 
     */
    public getType<T extends {new():Asset}>(bundleName:string,path:string,type:T):Promise<Asset>{
        return new Promise(async resolve=>{
            let  asset:Asset=null; 
            let loader_bundle:LoaderBundle=this.getLoaderBundle(bundleName)
            if(loader_bundle){
                asset=await loader_bundle.load(path,type)
            }
            resolve(asset);
        })
    }
     /**
     * 归还对象池laoder对象
     * @param path 
     */
    public release(path:string){
        let  loader:LoaderBundle=this.getLoaderBundle(path)
        if(loader){
            loader.clear();
        }
    }
}